<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12" :xs="24">
        <el-card shadow="never" class="bd0">
          <div class="title">企业信息</div>
          <div>
            <div style="margin-left: 131px;">
              <userAvatar />
            </div>
            <ul class="li_group">
              <li class="li_group_item">
                <div class="left_label">新爵仕网账号</div>
                <div class="right_value">{{ state.user.userName }}</div>
              </li>
              <li class="li_group_item">
                <div class="left_label">企业名称</div>
                <div class="right_value">{{ userForm.companyName }}</div>
              </li>
              <li class="li_group_item">
                <div class="left_label">所属行业</div>
                <div class="right_value">{{ userForm.industryName }}</div>
              </li>
              <li class="li_group_item">
                <div class="left_label">联系手机</div>
                <div class="right_value">{{ state.user.phone }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-card shadow="never" class="bd0">
          <ul class="li_group-right">
            <li class="li_group_right_item">
              <div class="left_label">成员账号</div>
              <div class="right_value blue-text">{{ state.user.userName }}</div>
            </li>
            <li class="li_group_right_item space_between">
              <div class="flex">
                <div class="left_label">登录密码</div>
                <div class="right_value">定期更换有助于提升账号安全</div>
              </div>
              <el-button class="btn" plain @click="dialogOpen('修改密码')">修改密码</el-button>
            </li>
            <li class="li_group_right_item space_between">
              <div class="flex">
                <div class="left_label">绑定手机</div>
                <div class="right_value">{{ desensitizationPhonenumber }}</div>
              </div>
              <el-button class="btn" plain @click="dialogOpen('修改绑定手机')">修改</el-button>
            </li>
          </ul>
        </el-card>
      </el-col>
    </el-row>
    <!-- 修改密码弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- 修改密码表单 -->
        <template v-if="dialog.title === '修改密码'">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input :type="pwdInputType0" v-model="form.oldPassword" placeholder="请输入旧密码">
              <template #suffix
                ><el-icon>
                  <Hide v-if="pwdInputType0 === 'password'" @click="togglePwdView0(pwdInputType0)" />
                  <View v-else @click="togglePwdView0(pwdInputType0)" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input :type="pwdInputType1" v-model="form.newPassword" placeholder="请输入新密码">
              <template #suffix
                ><el-icon>
                  <Hide v-if="pwdInputType1 === 'password'" @click="togglePwdView1(pwdInputType1)" />
                  <View v-else @click="togglePwdView1(pwdInputType1)" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmNewPassword">
            <el-input :type="pwdInputType2" v-model="form.confirmNewPassword" placeholder="请确认新密码">
              <template #suffix
                ><el-icon>
                  <Hide v-if="pwdInputType2 === 'password'" @click="togglePwdView2(pwdInputType2)" />
                  <View v-else @click="togglePwdView2(pwdInputType2)" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </template>
        <!-- 修改绑定手机号表单 -->
        <template v-else>
          <el-form-item label="绑定手机号" prop="bindPhone">
            <el-input v-model="form.bindPhone" placeholder="请输入绑定手机号" @blur="registerCheckPhoneFun($event)"></el-input>
          </el-form-item>
          <el-form-item label="短信验证码" prop="smsCode" style="position: relative;">
            <el-input size="large" v-model="form.smsCode" auto-complete="off" placeholder="请输入验证码"> </el-input>
            <div>
              <div class="get_code_Btn" :style="cmpStyle" type="text" @click.stop="getSmsCode">
                {{ codeText }}
              </div>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button @click="dialogClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Profile" lang="ts">
import UserAvatar from "./userAvatar.vue";
import { getAuthList } from "@/api/system/social/auth";
import { getUserProfile, updateUserPwd, updateUserProfile } from "@/api/system/user";
import { registerCheckPhone, sendAliyunNoUUid } from '@/api/login';

import useUserStore from '@/store/modules/user';
import useAppStore  from '@/store/modules/app';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userStore = useUserStore();
const appStore = useAppStore();

const state = ref<Record<string, any>>({
    user: {},
    roleGroup: '',
    postGroup: '',
    auths: []
});

const userForm = ref({});
const getUser = async () => {
    const res = await getUserProfile();
    state.value.user = res.data.user;
    userForm.value = { ...res.data.user, companyName: res.data.companyName, industryName: res.data.industryName }
    state.value.roleGroup = res.data.roleGroup;
    state.value.postGroup = res.data.postGroup;
};

const getAuths = async () => {
    const res = await getAuthList();
    state.value.auths = res.data;
};

// 修改密码弹窗
const dialog = ref({
  title: '修改密码',
  visible: false
})
// 修改密码表单
const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: '',
  bindPhone: '',
  smsCode: '',
})

// 新密码与确认密码是否一致
const isSame = ref(false)
// 确认新密码
const confirmNewPasswordValidator = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("请确认新密码"));
  } else if (form.value.newPassword !== value) {
    callback(new Error("两次输入的密码不一致"));
    isSame.value = false
  } else {
      isSame.value = true
    callback();
  }
}
const rules = {
  'oldPassword': [
    { required: true, trigger: 'blur', message: '请输入旧密码' },
  ],
  'newPassword': [
    { required: true, trigger: 'blur', message: '请输入新密码' },
  ],
  'confirmNewPassword': [
    { required: true, trigger: 'blur', validator: confirmNewPasswordValidator },
  ],
  'bindPhone': [
    { required: true, trigger: 'blur', message: '请输入绑定手机号' },
  ],
  smsCode: [{ required: true, trigger: 'blur', message: '请输入短信验证码' }],
}
// 开启弹窗
const dialogOpen = (val) => {
  dialog.value.visible = true
  dialog.value.title = val
}
const pwdInputType0 = ref('password')
const pwdInputType1 = ref('password')
const pwdInputType2 = ref('password')
// 密码可见切换
const togglePwdView0 = (temp) => {
  if (temp === 'password') pwdInputType0.value = 'text'
  else pwdInputType0.value = 'password'
}
const togglePwdView1 = (temp) => {
  if (temp === 'password') pwdInputType1.value = 'text'
  else pwdInputType1.value = 'password'
}
const togglePwdView2 = (temp) => {
  if (temp === 'password') pwdInputType2.value = 'text'
  else pwdInputType2.value = 'password'
}
const formRef = ref()
// 修改密码
const changePassword = async() => {
  formRef.value && formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const param = {
        phone: state.value.user.phonenumber,
        oldPassword: form.value.oldPassword,
        newPassword: form.value.newPassword,
      }
      try {
        const res = await updateUserPwd(param.phone, param.oldPassword, param.newPassword)
        proxy?.$modal.msgSuccess(res.msg);
        dialogClose()
        await userStore.logout()
        location.href = import.meta.env.VITE_APP_CONTEXT_PATH + 'index';
      } catch (error) {
        console.log(error);
      }
    }
  })
}
// 手机号脱敏
const desensitizationPhonenumber = computed(() => {
  if (state.value.user.phonenumber) {
    return state.value.user.phonenumber.slice(0, 3) + '****' + state.value.user.phonenumber.slice(7)
  }
})

// 是否已发送验证码
const isSend = ref(false)
// 定时器获取验证码
const timer = ref(null)
// 倒计时
const countDown = ref(60)
// 验证码文字
const codeText = ref('立即获取')
// 模板id，阿里云发短信业务用
const templateId = ref('')
// 手机号已重复注册
const isRepeat = ref(false)

/**
 * 获取图形验证码
 */
 const cmpStyle = computed(() => {
  if (!form.value.bindPhone) return { 'color': '#606266' }
  else return { 'color': countDown.value >= 60 ? '#096AFF' : '#606266' }
})

const registerCheckPhoneFun = async(e) => {
  if (e.target.value) {
    isRepeat.value = await userStore.registerCheckPhoneFun(form.value.bindPhone)
  }
}

// 获取手机验证码
const getSmsCode = async() => {
  if (!/^1[3|4|5|6|7|8|9]\d{9}$/.test(form.value.bindPhone)) return proxy?.$modal.msgError("请输入合法手机号");
  if (isRepeat.value) return proxy?.$modal.msgError("手机号已注册");
  if (isSend.value && timer.value) return
  let allTemplateIdMap  = await appStore.getTemplateId();
  try {
    const param = {
      phones: form.value.bindPhone,
      templateId: allTemplateIdMap['信息变更验证码'],
    }
    await sendAliyunNoUUid(param)
    isSend.value = true
    if (timer.value) clearInterval(timer.value)
    timer.value = setInterval(() => {
      countDown.value--
      codeText.value = `${countDown.value}s重新获取 `
      if (countDown.value === 0) {
        countDown.value = 60
        codeText.value = '重新获取'
        clearInterval(timer.value)
        timer.value = null
        isSend.value = false
      }
    }, 1000)
  } catch (error) {
    console.log(error);
    isSend.value = false
    if (timer.value) clearInterval(timer.value)
  }
}

// 修改绑定手机
const changebindPhoneNumber = async() => {
  formRef.value && formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const param = {
        phonenumber: form.value.bindPhone,
        smsCode: form.value.smsCode
      }
      try {
        await updateUserProfile(param)
        proxy?.$modal.msgSuccess("修改成功");
        dialogClose()
        getUser();
      } catch (error) {
        console.log(error);
      }
    }
  })
}

// 确认
const confirm = () => {
  if (dialog.value.title === '修改密码') changePassword()
  else changebindPhoneNumber()
}
// 取消
const dialogClose = () => {
  form.value.oldPassword = ''
  form.value.newPassword = ''
  form.value.confirmNewPassword = ''
  form.value.bindPhone = ''
  dialog.value.visible = false
  dialog.value.title = ''
}
onMounted(() => {
    getUser();
    getAuths();
})
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
})
</script>
<style lang="scss" scoped>
.bd0 {
  border: none;
}
:deep(.el-card__body) {
    padding: 24px !important;
    border: none;
    min-height: 538px;
}
.flex {
    display: flex;
    align-items: center;
}
.space_between {
    justify-content: space-between;
}
.title {
    font-weight: 500;
    font-size: 16px;
    color: #3D3D3D;
}
.li_group {
    .li_group_item {
        display: flex;
        align-items: center;
        margin-bottom: 48px;
        .left_label {
            min-width: 84px;
            font-weight: 500;
            font-size: 14px;
            color: #A8B0BC;
            margin-right: 32px;
        }
        .right_value {
            font-weight: 500;
            font-size: 14px;
            color: #3D3D3D;
        }
    }
}
.li_group-right {
  margin: 0;padding: 0;
    .li_group_right_item {
        display: flex;
        align-items: center;
        padding-bottom: 60px;
        border-bottom: 1px solid #F9F9F9;
        &:not(:nth-child(1)) {
            padding-top: 60px;
        }
        .left_label {
            font-weight: 500;
            font-size: 16px;
            color: #3D3D3D;
            margin-right: 48px;
        }
        .right_value {
            font-weight: 500;
            font-size: 16px;
            color: #A8B0BC;
        }
        .btn {
            width: fit-content;
            padding: 0 12px;
            height: 32px;
            line-height: 32px;
            border: 1px solid #096AFF;
            border-radius: 4px;
            text-align: center;
            color: #096AFF;
        }
    }
}
.blue-text {
    color: #096AFF!important;
}
.get_code_Btn {
  position: absolute;
  right: 25px;
  top: 50%;
  transform: translateY(-50%);
  padding: 0;
  font-weight: 400;
  font-size: 1.14rem;
  color: #096AFF;
  cursor: pointer;
}
</style>
